package com.educate.service.impl;

import com.educate.common.dto.CourseCoverDto;
import com.educate.common.dto.CourseTypeDto;
import com.educate.common.exception.Asserts;
import com.educate.common.lang.Const;
import com.educate.dao.CourseDao;
import com.educate.dao.UserDao;
import com.educate.pojo.Course;
import com.educate.pojo.User;
import com.educate.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yjj
 * @date 2021/11/22
 * @description: CourseServiceImp
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private UserDao userDao;

    /**
     * 添加课程及其封面
     * @param course
     * @return
     */
    @Override
    //多表操作，引入事务
    @Transactional
    public String addCourseCover(Course course) {
        //获取访问者的用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userDao.getUserInfoByUsername(username);
        //生成唯一绑定码
        String classId = UUID.randomUUID().toString().replace("-","").substring(0,5);
        course.setClassId(classId);
        //加入课程表
        courseDao.addCourseCover(course);
        //加入课程和老师用户连接表
        courseDao.teacherBindClass(user.getId(),course.getId());
        return classId;
    }

    /**
     * 学生加入班级
     * @param classId
     */

    @Override
    @Transactional
    public void studentBindClass(String classId) {
        //根据请求获取用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userDao.getUserInfoByUsername(username);
        //根据绑定码获取指定课程ID
        Course course = courseDao.selectCourseByClassId(classId);
        //将学生和此课程进行绑定
        courseDao.studentBindClass(user.getId(),course.getId());
    }


    /**
     * 获取在线课程
     * @return List<CourseTypeDto>
     */
    @Override
    public List<CourseTypeDto> getOnlineCourse() {
        return getCourse(courseDao.getOnlineCourse());
    }

    /**
     * 获取课程通用类
     * @return  List<CourseTypeDto>
     */

    @Override
    public List<CourseTypeDto> getCourse(List<Course> courseList) {
        List<CourseTypeDto> resultList = new ArrayList<>(); //返回结果集
        //课程类别去重
        Set<String> typeList = new HashSet<>();
        for (Course course : courseList) {
            typeList.add(course.getType());
        }
        int id = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //根据课程类别遍历，一个课程类别算一个组
        for (String type : typeList) {
            CourseTypeDto typeDto = new CourseTypeDto();  //每一个自定义的课程实体
            typeDto.setId(id++);
            typeDto.setType(type);
            //遍历查询的所有课程，并根据课程类别进行分组
            for (Course course : courseList) {
                if(type.equals(course.getType())){
                    //根据前端需要的数据进行自定义
                    CourseCoverDto dto = new CourseCoverDto();
                    dto.setId(id++);
                    dto.setCourseId(course.getId());
                    dto.setClassId(course.getClassId());
                    dto.setTitle(course.getTitle());
                    dto.setCover(Const.OSS_BASE_URL + course.getCover());
                    dto.setStartTime(sdf.format(course.getStartTime()));
                    String summary = course.getSummary();
                    if(summary == null){
                        summary = "";
                    }
                    dto.setSummary(summary);
                    String outline = course.getOutline();
                    if(outline == null){
                        outline = "";
                    }
                    dto.setOutline(outline);
                    //获取学习此课程学生的人数
                    int sum = courseDao.getStudySum(course.getId());
                    dto.setStudySum(sum);
                    //获取老师的基本信息
                    User teacher = courseDao.getTeacher(course.getId());
                    dto.setTeacher(teacher.getFullName());
                    dto.setAvatar(teacher.getAvatar());
                    typeDto.getList().add(dto);
                }
            }
            resultList.add(typeDto);
        }
        return resultList;
    }

    /**
     * 我的课程(老师)
     * @return List<CourseTypeDto>
     */
    @Override
    public List<CourseTypeDto> getTeacherCourse() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userDao.getUserInfoByUsername(username);
        List<Course> courseList = courseDao.getTeacherCourse(user.getId());
        return getCourse(courseList);
    }

    /**
     * 我的课程(学生)
     * @return List<CourseTypeDto>
     */
    @Override
    public List<CourseTypeDto> getStuCourse() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userDao.getUserInfoByUsername(username);
        List<Course> courseList = courseDao.getStudentCourse(user.getId());
        return getCourse(courseList);
    }

    /**
     * 删除课程
     * @param courseId
     */
    @Override
    @Transactional
    public void deleteCourse(Long courseId) {
        //获取访问者的用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        //获取角色
        Long roleId = userDao.getRoleIdByUserName(username);
        //获取用户
        User user = userDao.getUserInfoByUsername(username);
        //如果是角色是老师
        if(roleId == 1L){
            //解绑课程
            int flag1 = courseDao.deleteTeaCourseByIds(user.getId(),courseId);
            //删除课程基本信息
            int flag2 = courseDao.deleteCourseByCourseId(courseId);
            if(flag1 != flag2){
                Asserts.fail("删除失败！");
            }
        }
        //如果是角色是老师
        if(roleId == 2L){
            //解绑课程
            int flag = courseDao.deleteStuCourseByIds(user.getId(),courseId);
            if(flag != 1){
                Asserts.fail("删除失败！");
            }
        }
    }
}
